import { loginApi, getUserInfoApi } from '@/api/user'
import router from '@/router'
import { setToken, getToken, removeToken } from '@/utils/auth'
import { Message } from 'element-ui'
import { constantRoutes, resetRouter } from '@/router'
export default {
  namespaced: true,
  state() {
    return {
      token: getToken(),
      userInfo: {},
      routes: constantRoutes
    }
  },
  mutations: {
    // 1. 存token
    SET_TOKEN(state, token) {
      // 1.1 往本地存储token
      setToken(token)
      // 1.2 往state中存储token
      state.token = token
    },
    // 2. 删除token
    REMOVE_TOKEN(state) {
      removeToken()
      state.token = null
    },
    // 3. 获取用户信息
    SET_USER_INFO(state, userinfo) {
      state.userInfo = userinfo
    },
    // 4. 清除用户信息
    CLEAR_USER_INFO(state) {
      state.userInfo = {}
    },
    // 5. 设置路由
    SET_ROUTES(state, routes) {
      state.routes = [...constantRoutes, ...routes]
    }

  },
  actions: {
    // 1. 登录
    async login(context, { mobile, password }) {
      // 登录  进行跨域问题解决
      // const res = await request.post('/sys/login', { mobile, password })
      const token = await loginApi({ mobile, password })
      console.log(token)

      context.commit('SET_TOKEN', token)
      Message.success('登录成功')
      // 1.2 跳转到首页
      router.replace('/')
    },
    // 2. 退出登录
    async logout(context) {
      // 清除token
      context.commit('REMOVE_TOKEN')
      // 清除用户信息
      context.commit('CLEAR_USER_INFO')
      // 重置路由
      resetRouter()
    },
    // 3. 获取用户信息
    async getUserInfo(context) {
      const userInfo = await getUserInfoApi()
      context.commit('SET_USER_INFO', userInfo)
      return userInfo
    }
  }
}

